﻿using System;
using System.IO;
using System.Xml;
using Framework.Core.Logger;

namespace Framework.UI.Template.Common
{
    public class LanguageHelper
    {
        public LanguageHelper(string languageCode)
        {
            LanguageCode = languageCode;
            ConfigFile = GetLanguageConfigFileName();

            if (Document == null)
            {
                var file = new StreamReader(ConfigFile);
                Document = new XmlDocument();
                Document.Load(file);
            }
        }

        /// <summary>
        /// 存储多语言配置的XML文档
        /// </summary>
        public XmlDocument Document { get; set; }

        /// <summary>
        /// 多语言XML配置文件名
        /// </summary>
        public string ConfigFile { get; set; }

        /// <summary>
        /// 语言代码
        /// </summary>
        public string LanguageCode { get; set; }


        /// <summary>
        /// 根据语言代码获取相关配置文件名
        /// </summary>
        /// <returns></returns>
        private string GetLanguageConfigFileName()
        {
            return string.Format(@"Languages\Language_{0}.xml", LanguageCode);
        }

        /// <summary>
        /// 从配置文件中获取
        /// </summary>
        /// <param name="sectionName"></param>
        /// <param name="configName"></param>
        /// <returns></returns>
        public string GetLanguageString(string sectionName, string configName)
        {
            string result = "";
            try
            {
                XmlNodeList configNodes = Document.SelectNodes("//" + configName);
                if (configNodes != null)
                    foreach (XmlNode node in configNodes)
                    {
                        if (node.ParentNode != null)
                            if (node.Name == configName && node.ParentNode.Name == sectionName)
                            {
                                result = node.InnerText;
                                break;
                            }
                    }
            }
            catch (Exception e)
            {
                LogHelper.WriteExceptionLog(e.Message);
            }
            return result;
        }
    }
}